package me.leiusual.sharing.ui.mine

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavDirections
import androidx.navigation.fragment.findNavController
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_mine_home.*
import me.leiusual.sharing.R
import me.leiusual.sharing.api.model.RegisterByQRCode
import me.leiusual.sharing.api.model.usertotal.UserTotal
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.ScanActivity
import me.leiusual.sharing.ui.account.AccountLoginFragment
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.util.extension.setImageUrl
import me.leiusual.sharing.util.extension.toImplicitRealName
import me.leiusual.sharing.util.extension.toast
import timber.log.Timber
import javax.inject.Inject

/**
 * Create by leiusual on 2018/7/15
 */
class MineHomeFragment : DaggerFragment(), View.OnClickListener {

  companion object {
    private const val REQ_SCAN = 1
  }

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val viewModel: MineHomeViewModel by viewModels { factory }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_mine_home, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }
    toolbar.setOnMenuItemClickListener {
      when (it.itemId) {
        R.id.action_setting -> {
          dispatchNavigate(MineHomeFragmentDirections.actionMineHomeFragmentToSettingHomeFragment())
          true
        }
        else -> false
      }
    }

    layout_mine_info.setOnClickListener(this)

    text_view_order_pay.setOnClickListener(this)
    text_view_order_send.setOnClickListener(this)
    text_view_order_receive.setOnClickListener(this)
    text_view_order_all.setOnClickListener(this)

    text_view_scan_qr_code.setOnClickListener(this)
    text_view_address.setOnClickListener(this)
    text_view_auth.setOnClickListener(this)
    text_view_invite.setOnClickListener(this)
    text_view_message.setOnClickListener(this)
    text_view_user_account.setOnClickListener(this)
    text_view_business.setOnClickListener(this)
    text_view_business_apply.setOnClickListener(this)

    observeData()
    viewModel.userInfo()
    viewModel.userTotal()
  }

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    Timber.v("onActivityResult %s, %s, %s", requestCode, resultCode, data)

    if (requestCode == REQ_SCAN && resultCode == Activity.RESULT_OK) {
      val text = ScanActivity.getResult(data) ?: return
      try {
        val uri = Uri.parse(text)
        val encodedClientId = uri.getQueryParameter("client_id") ?: return
        val inviteCode = uri.getQueryParameter("ic") ?: return
        viewModel.registerByQRCode(encodedClientId, inviteCode)
      } catch (e: Throwable) {
        Timber.w(e)
      }
    }
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.layout_mine_info -> {
        dispatchNavigate(MineHomeFragmentDirections.actionMineHomeFragmentToMineInfoFragment())
      }

      R.id.text_view_order_pay -> {
        // 待支付
        dispatchNavigate(MineHomeFragmentDirections.actionMineHomeFragmentToOrderHomeFragment(0, 0))
      }
      R.id.text_view_order_send -> {
        // 待发货
        dispatchNavigate(MineHomeFragmentDirections.actionMineHomeFragmentToOrderHomeFragment(1, 0))
      }
      R.id.text_view_order_receive -> {
        // 待收货
        dispatchNavigate(MineHomeFragmentDirections.actionMineHomeFragmentToOrderHomeFragment(2, 0))
      }
      R.id.text_view_order_all -> {
        // 全部
        dispatchNavigate(MineHomeFragmentDirections.actionMineHomeFragmentToOrderHomeFragment(3, 0))
      }

      R.id.text_view_scan_qr_code -> {
        startActivityForResult(ScanActivity.intent(v.context), REQ_SCAN)
      }
      R.id.text_view_address -> {
        // 地址管理
        dispatchNavigate(MineHomeFragmentDirections.actionMineHomeFragmentToMineAddressFragment())
      }
      R.id.text_view_auth -> {
        dispatchNavigate(MineHomeFragmentDirections.actionMineHomeFragmentToMineAuthFragment())
      }
      R.id.text_view_invite -> {
        dispatchNavigate(MineHomeFragmentDirections.actionMineHomeFragmentToMineInviteFragment())
      }
      R.id.text_view_message -> {
        dispatchNavigate(MineHomeFragmentDirections.actionMineHomeFragmentToMineMessageFragment())
      }
      R.id.text_view_user_account -> {
        dispatchNavigate(MineHomeFragmentDirections.actionMineHomeFragmentToUserAccountFragment("user"))
      }

      R.id.text_view_business_apply -> {
        dispatchNavigate(MineHomeFragmentDirections.actionMineHomeFragmentToShopApplyFragment())
      }
      R.id.text_view_business -> {
        // 我的店铺
        dispatchNavigate(MineHomeFragmentDirections.actionMineHomeFragmentToShopManageFragment())
      }
    }
  }

  private fun dispatchNavigate(action: NavDirections) {
    if (viewModel.token.isLogin) {
      findNavController().navigate(action)
    } else {
      findNavController().navigate(R.id.action_global_accountLoginFragment)
    }
  }

  private fun observeData() {
    viewModel.userInfo.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("userInfo = %s", it)
      when (it) {
        is Data.Loading -> {
          updateUserInfo()
        }
        is Data.Error -> {
          updateUserInfo()
        }
        is Data.Success -> {
          updateUserInfo()
        }
      }
    })

    viewModel.userTotal.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("userTotal = %s", it)
      when (it) {
        is Data.Loading -> {
          // ignore
        }
        is Data.Error -> {
          // ignore
        }
        is Data.Success -> {
          updateUserTotal(it.data)
        }
      }
    })

    viewModel.registerByQRCode.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("registerByQRCode = %s", it)
      when (it) {
        is Data.Loading -> {
          toast("注册用户中，请稍等...")
        }
        is Data.Error -> {
          toast(it.error.message)
        }
        is Data.Success -> {
          showRegisterResult(it.data)
        }
      }
    })
  }

  private fun updateUserInfo() {
    if (viewModel.token.isLogin) {
      val nickname = viewModel.user.nickname
      val username = viewModel.user.username
      if (nickname.isNullOrBlank()) {
        text_view_name.text = username
      } else {
        text_view_name.text = "$nickname($username)"
      }

      val realName = viewModel.user.realName
      text_view_tag_auth.text = if (realName.isNullOrBlank()) "未实名认证" else "实名：${realName.toImplicitRealName()}"
      text_view_tag_auth.isVisible = true
      image_view_header.setImageUrl(viewModel.user.avatar)

    } else {
      text_view_name.text = "点击登录"

      text_view_tag_auth.text = ""
      text_view_tag_auth.isVisible = false
      image_view_header.setImageUrl(R.drawable.ic_logo)
    }
  }

  private fun updateUserTotal(data: UserTotal) {

    // 更新邀请人
    if (data.invitor == null) {
      text_view_invitor.isVisible = false
    } else {
      text_view_invitor.isVisible = true
      text_view_invitor.text = """邀请人：${data.invitor}"""
    }

    // 更新数量
    text_view_order_pay_count.isVisible = false
    text_view_order_send_count.isVisible = false
    text_view_order_receive_count.isVisible = false
    text_view_message_count.isVisible = false

    data.totalItems.forEach {
      when (it.totalType) {
        "PAYING_ORDER_TOTAL" -> {
          if (it.total > 0) {
            text_view_order_pay_count.isVisible = true
            text_view_order_pay_count.text = it.total.toString()
          }
        }
        "SENDING_ORDER_TOTAL" -> {
          if (it.total > 0) {
            text_view_order_send_count.isVisible = true
            text_view_order_send_count.text = it.total.toString()
          }
        }
        "RECEIPTING_ORDER_TOTAL" -> {
          if (it.total > 0) {
            text_view_order_receive_count.isVisible = true
            text_view_order_receive_count.text = it.total.toString()
          }
        }
        "USER_MESSAGE_TOTAL" -> {
          if (it.total > 0) {
            text_view_message_count.isVisible = true
            text_view_message_count.text = it.total.toString()
          }
        }
      }
    }

    // 更新店铺状态
    if (data.storeId == null) {
      text_view_business_apply.isVisible = true
      text_view_business.isVisible = false
    } else {
      text_view_business_apply.isVisible = false
      text_view_business.isVisible = true
    }

    // 更新所有店铺列表
    viewModel.store.storeList = data.storeOptions

    // 更新可管理店铺列表
    viewModel.store.managedStoreList = data.storeOptions.toMutableMap().apply {
      data.unmanagedStoreIds.forEach { unmanagedStoreId ->
        val value = remove(unmanagedStoreId)
        Timber.v("remove %s", value)
      }
    }
  }

  private fun showRegisterResult(data: RegisterByQRCode.Response) {
    val message = if (data.invitor == null) {
      "登录帐号：${data.username}\n登录密码：${data.originPassword}"
    } else {
      "邀请人：${data.invitor}\n登录帐号：${data.username}\n登录密码：${data.originPassword}"
    }
    AlertDialog.Builder(requireContext())
        .setMessage(message)
        .setPositiveButton("确认") { _, _ ->
          if (!viewModel.token.isLogin) {
            val args = Bundle()
            args.putString(AccountLoginFragment.USERNAME, data.username)
            args.putString(AccountLoginFragment.PASSWORD, data.originPassword)
            findNavController().navigate(R.id.action_global_accountLoginFragment, args)
          }
        }
        .setCancelable(false)
        .show()
  }
}